<template>
  <ul ref="blockList" class="cml-panel-content" v-if="showBlock">
    <slot v-bind:options="options"></slot>
  </ul>
</template>
<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'CmlCollapse',
  components: {},
  model: {},
  inheritAttrs: false,
  provide() {
    return {
      options: this.options
    }
  },
  props: {
    defaultOpeneds: {
      type: [Array, String]
    },
    uniqueOpened: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: {
        defaultOpeneds: this.defaultOpeneds, // 通过组件传递的参数优先级高
        uniqueOpened: this.uniqueOpened, // 通过组件传递的参数优先级高
        change: this.change, // function
        groupId: this._uid // number
      },
      showBlock: true
    }
  },
  computed: {
    ...mapState('cmlpanel', ['collapseData'])
  },
  watch: {},
  beforeCreate() {},
  created() {},
  mounted() {
    // console.log(this.$slots.default[0].child)
    this.openByOrder(0)
  },
  updated() {
    // this.checkChild()
  },
  beforeDestroy() {},
  methods: {
    ...mapMutations('cmlpanel', [
      'setBlockDefaultOpen',
      'setBlockUniqOpen',
      'addBlockGroupInfo',
      'removeBlockInfo',
      'removeBlockUniqInfo'
    ]),
    init() {
      if (this.defaultOpeneds) {
        this.setBlockDefaultOpen(this.defaultOpeneds)
      }
      if (this.uniqueOpened) {
        this.setBlockUniqOpen(this.uniqueOpened)
      }
    },
    // 子模块展开或者折叠的事件
    change(index, statu) {
      this.$emit('change', { index, statu })
    },
    open(index) {
      let unq = this.collapseData.uniqueOpened
      if (unq) {
        this.removeBlockUniqInfo({ name: `_${this._uid}`, data: index })
      } else {
        this.addBlockGroupInfo({ name: `_${this._uid}`, data: index })
      }
    },
    close(index) {
      this.removeBlockInfo({ name: `_${this._uid}`, data: index })
    },
    toggleCollapse(index) {
      let currentGroup = this.collapseData.group[`_${this._uid}`]
      if (currentGroup.includes(index)) {
        this.close(index)
      } else {
        this.open(index)
      }
    },
    // todo
    openByOrder(order) {
      order = parseInt(order)
      const child = this.$slots.default[order].child
    },
    closeByOrder(order) {},
    toggleByOrder(order) {},
    checkChild() {
      let childNodes = this.$refs.blockList && this.$refs.blockList.childNodes
      let usefulNodes = [...childNodes].filter((n) => {
        console.log(n.nodeType)
        return n.nodeType === 1
      })
      if (usefulNodes.length) {
        this.showBlock = true
      } else {
        this.showBlock = false
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
